import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import {
  markSystemMessageRead,
  markSystemMessagesRead,
  getSystemUnreadCount,
  markMessagesAsRead,
  getSessionUnreadCount
} from './apiService'
import chatWebSocket from './websocket'

/**
 * 全局消息状态管理器
 * 统一管理系统消息和聊天消息的状态
 */
class MessageStateManager {
  constructor() {
    // 系统消息状态
    this.systemMessages = ref([])
    this.systemUnreadCount = ref(0)
    
    // 聊天消息状态
    this.chatSessions = ref([])
    this.chatUnreadCounts = reactive({}) // sessionId -> unreadCount
    
    // 状态更新回调
    this.stateUpdateCallbacks = new Set()
    
    // 初始化WebSocket监听
    this.initWebSocketListeners()
  }

  /**
   * 初始化WebSocket监听器
   */
  initWebSocketListeners() {
    // 监听系统通知
    chatWebSocket.addNotificationHandler('global-state-manager', (notification) => {
      this.handleNewSystemNotification(notification)
    })

    // 监听未读消息更新
    chatWebSocket.addUnreadHandler('global-state-manager', (unreadData) => {
      this.updateChatUnreadCount(unreadData.sessionId, unreadData.count)
    })
  }

  /**
   * 处理新的系统通知
   */
  handleNewSystemNotification(notification) {
    // 增加系统消息未读数量
    this.systemUnreadCount.value++
    
    // 通知状态更新
    this.notifyStateUpdate('system', 'new_message', notification)
    
    console.log('收到新系统通知，未读数量:', this.systemUnreadCount.value)
  }

  /**
   * 更新聊天未读数量
   */
  updateChatUnreadCount(sessionId, count) {
    this.chatUnreadCounts[sessionId] = count
    
    // 更新会话列表中的未读数量
    const session = this.chatSessions.value.find(s => s.sessionId === sessionId)
    if (session) {
      session.unreadCount = count
    }
    
    // 通知状态更新
    this.notifyStateUpdate('chat', 'unread_count_update', { sessionId, count })
    
    console.log(`会话 ${sessionId} 未读数量更新为:`, count)
  }

  /**
   * 标记系统消息为已读
   */
  async markSystemMessageAsRead(messageId) {
    try {
      const response = await markSystemMessageRead(messageId)
      
      if (response.data.code === 200 || response.data.code === '200') {
        // 更新本地状态
        const message = this.systemMessages.value.find(m => m.messageId === messageId)
        if (message && !message.isRead) {
          message.isRead = true
          this.systemUnreadCount.value = Math.max(0, this.systemUnreadCount.value - 1)
        }
        
        // 通知状态更新
        this.notifyStateUpdate('system', 'mark_read', { messageId })
        
        return true
      } else {
        throw new Error(response.data.message || '标记失败')
      }
    } catch (error) {
      console.error('标记系统消息已读失败:', error)
      ElMessage.error('标记已读失败')
      return false
    }
  }

  /**
   * 批量标记系统消息为已读
   */
  async markSystemMessagesAsRead(messageIds) {
    try {
      const response = await markSystemMessagesRead(messageIds)
      
      if (response.data.code === 200 || response.data.code === '200') {
        // 更新本地状态
        let markedCount = 0
        messageIds.forEach(messageId => {
          const message = this.systemMessages.value.find(m => m.messageId === messageId)
          if (message && !message.isRead) {
            message.isRead = true
            markedCount++
          }
        })
        
        this.systemUnreadCount.value = Math.max(0, this.systemUnreadCount.value - markedCount)
        
        // 通知状态更新
        this.notifyStateUpdate('system', 'batch_mark_read', { messageIds, markedCount })
        
        return true
      } else {
        throw new Error(response.data.message || '批量标记失败')
      }
    } catch (error) {
      console.error('批量标记系统消息已读失败:', error)
      ElMessage.error('批量标记失败')
      return false
    }
  }

  /**
   * 标记聊天消息为已读
   */
  async markChatAsRead(sessionId) {
    try {
      const response = await markMessagesAsRead(sessionId)

      if (response.data.code === 200 || response.data.code === '200') {
        // 更新本地状态
        this.updateChatUnreadCount(sessionId, 0)

        // 通知状态更新
        this.notifyStateUpdate('chat', 'mark_read', { sessionId })

        return true
      } else {
        throw new Error(response.data.message || '标记失败')
      }
    } catch (error) {
      console.error('标记聊天消息已读失败:', error)
      ElMessage.error('标记已读失败')
      return false
    }
  }

  /**
   * 刷新系统消息未读数量
   */
  async refreshSystemUnreadCount() {
    try {
      const response = await getSystemUnreadCount()
      
      if (response.data.code === 200 || response.data.code === '200') {
        this.systemUnreadCount.value = response.data.data.unreadCount || 0
        
        // 通知状态更新
        this.notifyStateUpdate('system', 'unread_count_refresh', { 
          count: this.systemUnreadCount.value 
        })
        
        return this.systemUnreadCount.value
      }
    } catch (error) {
      console.error('刷新系统消息未读数量失败:', error)
    }
    return 0
  }

  /**
   * 刷新聊天未读数量
   */
  async refreshChatUnreadCount(sessionId) {
    try {
      const response = await getSessionUnreadCount(sessionId)

      if (response.data.code === 200 || response.data.code === '200') {
        const count = response.data.data.unreadCount || 0
        this.updateChatUnreadCount(sessionId, count)
        return count
      }
    } catch (error) {
      console.error('刷新聊天未读数量失败:', error)
    }
    return 0
  }

  /**
   * 获取总未读数量
   */
  getTotalUnreadCount() {
    const chatUnreadTotal = Object.values(this.chatUnreadCounts).reduce((sum, count) => sum + count, 0)
    return this.systemUnreadCount.value + chatUnreadTotal
  }

  /**
   * 添加状态更新回调
   */
  addStateUpdateCallback(callback) {
    this.stateUpdateCallbacks.add(callback)
  }

  /**
   * 移除状态更新回调
   */
  removeStateUpdateCallback(callback) {
    this.stateUpdateCallbacks.delete(callback)
  }

  /**
   * 通知状态更新
   */
  notifyStateUpdate(type, action, data) {
    this.stateUpdateCallbacks.forEach(callback => {
      try {
        callback({ type, action, data })
      } catch (error) {
        console.error('状态更新回调执行失败:', error)
      }
    })
  }

  /**
   * 清理资源
   */
  cleanup() {
    chatWebSocket.removeNotificationHandler('global-state-manager')
    chatWebSocket.removeUnreadHandler('global-state-manager')
    this.stateUpdateCallbacks.clear()
  }
}

// 创建全局实例
const messageStateManager = new MessageStateManager()

export default messageStateManager
